/* Copyright (C) 2011  Till Schoenbein mail: tschoenbein[at]gmail.com
	This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.*/

package de.shb;

import java.io.File;
import java.sql.SQLException;
import java.text.MessageFormat;

import de.shb.database.RequestBean;
import de.shb.database.RequestManager;
import de.shb.dice.DiceResult;
import de.shb.image.ImageCreator;
import de.shb.image.ImageSystem;

public class DiceGenerator implements IDiceGenerator {

	public static void main(String[] args) {
		DiceGenerator gen = new DiceGenerator();
		gen.execute("666", "333", "3W6");
	}

	@Override
	public File execute(String topic, String post, String dices) {
		RequestManager manager = RequestManager.getInstance();
		Object[] arguments = new Object[3];
		arguments[0] = topic;
		arguments[1] = post;
		RequestBean[] beans;
		try {
			beans = manager.loadByWhere(MessageFormat.format(
					"WHERE ThreadID = {0} AND PostID = {1}", (arguments)));

			System.out.println("INFO DiceGenerator.checkPermission "
					+ beans.toString() + ", Length: " + beans.length);

			if (beans.length == 0) {
				return generateImage(dices, topic, post, new DiceResult(dices));
			} else {
				RequestBean bean = beans[0];
				System.out.println("INFO DiceGenerator.checkPermission "
						+ bean.toString());
				return ImageSystem.returnImage(topic, post);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return ImageSystem.returnFailureImage();
		}

	}

	public File generateImage(String dices, String topic, String post,
			DiceResult diceResult) {
		Object[] arguments = new Object[5];
		arguments[0] = dices.substring(0, dices.indexOf("W"));
		;
		arguments[1] = dices.substring(dices.indexOf("W") + 1);
		;
		arguments[2] = topic;
		arguments[3] = post;
		arguments[4] = System.currentTimeMillis();

		ImageCreator creator = new ImageCreator();
		return creator.createImage(diceResult, buildImageName(topic, post),
				arguments);
	}

	private String buildImageName(String topic, String post) {
		StringBuilder builder = new StringBuilder();
		builder.append(topic);
		builder.append("_");
		builder.append(post);
		return builder.toString();
	}

}
